<template>
  <div class="delimit" @mouseup="selectArea($event)" @mouseleave="setShow(false)">
    <div class="item left">
      <div class="text-item title">{{title}}</div>
      <div class="text-item text-content" ref="contentText" :key="file && file.id">{{content}}</div>
      <!--@mouseup.stop="selectArea($event)"-->
    </div>
    <div class="item right">
      <div class="title">标注结果</div>
      <table>
        <thead>
          <tr class="tr">
            <th v-for="(item, index) in columns" :key="index" :class="'tr' + index">{{item.value}}</th>
            <th class="tr3">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="(item, key) in errorList"
            :key="key"
            class="tr"
            @mouseenter="setActiveText($event, item)"
            @mouseleave="removeActiveText"
          >
            <td class="tr0">{{ item.org }}</td>
            <td class="tr1">
              <Cascader
                :data="selects"
                :clearable="false"
                @on-change="setKey($event, item)"
                :render-format="format"
                :value="item.type"
              ></Cascader>
            </td>
            <td class="tr2">
              <Input v-model="item.correction" type="textarea" placeholder="修改内容" @on-change="changeValue"/>
            </td>
            <td class="tr3 delete-box">
              <i class="delete iconfont icon-icon_empty" @click="deleteItem(item)" title="删除"></i>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="select-box" v-show="showBox" ref="selectBox">
      <Cascader
        :data="selects"
        trigger="hover"
        element-id="select-box-input"
        @on-change="setSign"
        ref="cascader"
      ></Cascader>
    </div>
  </div>
</template>

<script>
import { getSourceData } from '../common';
export default {
  name: 'delimitItem',
  props: ['data', 'index', 'file', 'view', 'drag'],
  data () {
    return {
      showBox: false,
      errorList: [],
      currentSelectObj: {},
      columns: [
        {
          value: '错误',
          label: 'error'
        },
        {
          value: '错误类型',
          label: 'type'
        },
        {
          value: '修改内容',
          label: 'correction'
        }
      ],
      title: '', // 标题
      content: '', // 内容
      maxIndex: 0, // 最大的index
      selects: [],
      select: [{
        value: 'wordError',
        label: '单词错误',
        children: [
          {
            value: 'sinogramError',
            label: '汉字错误'
          },
          {
            value: 'englishError',
            label: '英文错误'
          },
          {
            value: 'symbolError',
            label: '符号错误'
          }
        ]
      }, {
        value: 'sentenceError',
        label: '句子错误',
        children: [
          {
            value: 'semanticError',
            label: '语义错误'
          },
          {
            value: 'vague',
            label: '表达不通'
          }
        ]
      }]
    }
  },
  created () {
    this.dataHandle(); // 数据预处理
  },
  watch: {
    'data.config': {
      handler: function (val, oldVal) {
        this.updateBaseDate()
      },
      deep: true
    },
    file: {
      handler: function (val, oldVal) {
        this.dataHandle(); // 数据预处理
      }
    }
  },
  methods: {
    // 更新配置数据
    updateBaseDate () {
      if (!this.view) {
        this.title = this.data.config.title;
        this.content = this.data.config.content;
        this.selects = [];
      }
    },
    // 数据处理
    dataHandle () {
      if (!this.view) { // 代表拖拽过程中
        this.title = this.data.config.title;
        this.content = this.data.config.content;
        this.selects = [];
      } else {
        const that = this;
        // const databinding = that.data.databinding;
        const contentSource = that.data.config.contentSource || '';
        const selectSource = that.data.config.selectSource || '';
        const isDefaultData = that.file.isDefaultData;
        const id = that.data.id;
        that.title = that.data.config.title;
        try {
          that.content = getSourceData(that.file.extend, contentSource) || '';
          that.selects = getSourceData(that.file.extend, selectSource) || that.select;
        } catch (e) {
          that.$Message.error('缺少必要字段');
        }

        if (!that.content || that.selects.length < 1) {
          that.$Message.error('缺少必要字段');
        }

        if (isDefaultData) { // 目前看来可能为空
          that.errorList = [];
        } else {
          that.errorList = that.file.result[id].value;
          that.getMaxIndex();
        }
        this.changeValue(); // 同步数据不然数据丢失
      }
    },
    // 获取最大的index
    getMaxIndex () {
      let maxIndex = this.maxIndex;
      this.errorList.forEach(function (item) {
        if (item.index > maxIndex) {
          maxIndex = item.index;
        }
      });
      this.maxIndex = maxIndex;
    },
    setItemStyle (styleObject) {
      if (!this.isObject(styleObject)) {
        return '';
      }
      return styleObject;
    },
    // 设置颜色
    setActiveText (event, item) {
      const start = item.start;
      const end = item.end;
      const target = this.$refs['contentText'];
      const text = target.innerText;
      const content = item.org;
      this.$refs['contentText'].innerHTML = text.substr(0, start) + `<span style="background: #FDFD64">${content}</span>` + text.substr(end, text.length);
    },
    // 移除文本颜色
    removeActiveText () {
      const target = this.$refs['contentText'].innerHTML;
      this.$refs['contentText'].innerHTML = target.replace(/<span[^<>]+>(.*?)<\/span>/g, function (item, content) {
        return content
      });
    },
    isObject (data) {
      return Object.prototype.toString.call(data) === '[object Object]';
    },
    format (labels, selectedData) {
      const index = labels.length - 1;
      const data = selectedData[index] || false;
      if (data && data.code) {
        return labels[index] + ' - ' + data.code;
      }
      return labels[index];
    },
    setKey (value, item) {
      item.type = value;
      this.changeValue(); // 修改值
    },
    // 选择时 所以 value 不能为空, 所以做一次判断
    setSign (value, selectedData) {
      if (value && value.length > 0) {
        this.currentSelectObj.type = value;
        this.errorList.push(this.currentSelectObj);
        this.currentSelectObj = {};
        this.setShow(false);
        this.clearSelect(); // 调用组件的方法清空选择的值1
        this.changeValue(); // 修改值
      }
    },
    clearSelect () {
      let clearSelect = this.$refs['cascader'].clearSelect;
      if (typeof clearSelect === 'function') {
        clearSelect()
      }
    },
    setShow (value) {
      this.showBox = value;
    },
    // 为了健壮性 原因 只有前后两个元素都是目标元素才理解为 是目标元素  同时 事件代理为了 保证既能消失又能展示
    isTarget (baseNode) {
      return baseNode.parentNode.className && baseNode.parentNode.className.indexOf('text-content') > -1
    },
    selectArea (event) {
      if (window.getSelection && !this.drag) {
        event.stopPropagation();
        const selection = window.getSelection();
        const focusNode = selection.focusNode; // 结束位置部分所属的节点
        const anchorNode = selection.anchorNode; // 开始位置所属的节点
        const anchorOffset = selection.anchorOffset; // 起点偏移量
        const focusOffset = selection.focusOffset; // 终点偏移量
        const selectText = selection.toString();
        // this.currentSelectObj = {}; // 两次触发的话 出现问题
        const start = (anchorOffset < focusOffset) ? anchorOffset : focusOffset;
        const end = (anchorOffset < focusOffset) ? focusOffset : anchorOffset;
        // if (!selectText) {
        //   return;
        // }
        if (focusNode.nodeType === 3 && anchorNode.nodeType === 3 && this.isTarget(anchorNode) && this.isTarget(focusNode)) {
          if (anchorOffset !== focusOffset) {
            this.maxIndex++;
            this.currentSelectObj = {
              start: start,
              end: end,
              type: [],
              org: selectText,
              index: this.maxIndex,
              correction: ''
            };
            this.setShow(true);
            this.setPos(event);
          } else {
            this.setShow(false);
          }
        } else {
          this.setShow(false);
        }
      } else {
        this.setShow(false);
      }
    },
    // 设置弹框位置
    setPos (event) {
      let oX = event.offsetX + 50;
      let oY = event.offsetY;
      this.$refs['selectBox'].style.left = oX + 'px';
      this.$refs['selectBox'].style.top = oY + 'px';
    },
    // 删除
    deleteItem (item) {
      const index = this.errorList.indexOf(item);
      this.errorList.splice(index, 1);
      this.removeActiveText();
      this.changeValue();
    },
    // 校验
    validate () {
      return true
    },
    // 数据更新
    changeValue () {
      let value = this.errorList;
      this.$emit('updateResult', {
        value,
        index: this.index
      });
    }
  },
  components: {

  }
}
</script>

<style lang="less">
/*.vue-grid-item{*/
/*overflow: scroll;*/
/*}*/
#select-box-input {
  display: none;
}

.delimit {
  display: flex;
  position: relative;
  height: 100%;
  .item {
    flex: 1;
    overflow: auto;
    .text-content {
      display: inline-block;
      font-size: 24px;
      color: #3e3e3e;
    }
    table {
      width: 100%;
      border-collapse: collapse;
      border-bottom: 1px solid #ececec;
      border-right: 1px solid #ececec;
      td,
      th {
        border: 1px solid #ececec;
        border-right: none;
        border-bottom: none;
        padding: 5px;
      }
    }
    .tr {
      display: flex;
      text-align: center;
      word-break: break-all;
      .delete-box {
        display: flex;
        .delete {
          display: inline-block;
          margin: 0 auto;
          align-self: center;
          background-size: auto 100%;
          cursor: pointer;
          &:hover {
            background-size: auto 100%;
            color: red;
          }
        }
      }
      .tr0 {
        flex: 1;
      }
      .tr1 {
        flex: 2;
      }
      .tr2 {
        flex: 2;
      }
      .tr3 {
        flex: 1;
      }
    }
    .title {
      line-height: 30px;
      font-size: 12px;
    }
  }
  .left,
  .right {
    background: #f8fafa;
    border: 1px solid #e3e3e3;
    padding: 10px;
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.06);
  }
  .right {
    margin-left: 10px;
  }
  .select-box {
    position: absolute;
    top: 0;
    left: 0;
    .ivu-cascader-rel {
      display: none;
      width: 0;
      height: 0;
    }
    .ivu-select-dropdown {
      display: block !important;
      left: 0 !important;
      top: 0 !important;
    }
    #select-box-input {
      display: block !important;
    }
  }
  textarea {
    resize: none;
  }
}
</style>
